<?php

namespace app\controller\admin\run;

use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\Exception;

/**
 * Class Game
 * @package app\controller\admin\run
 */
class Prop extends Backend
{
    /**
     * api_log模型对象
     * @var \app\model\api\Log
     */
    protected $model;
    protected $hasSoftDel=0;//是否拥有软删除功能

    protected $noNeedLogin = []; // 无需登录即可请求的方法
    protected $noNeedAuth = ['index', 'info']; // 无需鉴权即可请求的方法

    public $orderRule = ['id' => 'asc'];

    public function _initialize()
    {
        $this->model = new \app\model\admin\run\Prop();
    }

    /**
     * 列表
     *  all_data参数的值为true时，表示查询表中所有数据集，否则进行分页查询
     * @return mixed
     */
    public function index()
    {
        $where   = $this->buildSearchParams();
        $order   = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            $data  = $this->model->where($where)->order($order)->paginate($limit)->toArray();

            $gameName = (new \app\model\admin\run\Game())->column('name','id');
            array_walk($data['data'],function(&$item,$key) use ($gameName){
                $item['icon'] = self::imgUrlToAbsolute($item['icon']);
                $item['game_name'] = $gameName[$item['game_id']];
            });
        }
        return $this->success('数据获取成功', $data);
    }


    //添加
    public function add()
    {
        $post = CommonFun::filterPostData($this->request->post());

        try{
            if(empty($post['game_id']) || empty($post['min_level']) || empty($post['max_level'])){
                throw new Exception("参数不正确");
            }
            if ($prop_id = $this->model->strict(false)->insertGetId($post)) {
                (new \app\model\admin\run\Proplevel())->initPropLevel(
                    $prop_id,
                    $post['game_id'],
                    $post['min_level'],
                    $post['max_level']
                );
                $this->clearCache();
                return $this->success('添加成功', $post);
            } else {
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

}